<template>
  <div class="file-convert">
    <header class="header">
      <div class="header-content">
        <router-link to="/" class="back-button">
          <el-button icon="el-icon-back">返回首页</el-button>
        </router-link>
        <div class="title-container">
          <h1>文件格式转换</h1>
          <p class="subtitle">支持多种文件格式转换，快速且高效</p>
        </div>
      </div>
    </header>

    <el-card class="upload-card">
      <el-upload
        class="upload-area"
        drag
        :action="`/api/file/upload`"
        :headers="{
          'Accept': 'application/json'
        }"
        :on-success="handleUploadSuccess"
        :on-error="handleError"
        :before-upload="beforeUpload"
        :show-file-list="true"
        :auto-upload="false"
        ref="uploadRef"
      >
        <div class="upload-content">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="upload-text">
            <h3>点击或拖拽文件到此处</h3>
            <p>支持单个或多个文件上传</p>
          </div>
        </div>
      </el-upload>
      
      <div class="convert-options">
        <h3>选择目标格式：</h3>
        <div class="format-buttons">
          <el-radio-group v-model="targetFormat" size="large">
            <el-radio-button label=".pdf">PDF</el-radio-button>
            <el-radio-button label=".docx">DOCX</el-radio-button>
            <el-radio-button label=".txt">TXT</el-radio-button>
          </el-radio-group>
        </div>
        <el-button type="primary" size="large" class="convert-button" @click="startConvert">
          开始转换
        </el-button>
      </div>
    </el-card>

    <el-dialog v-model="showProgress" title="转换进度" width="500px" :close-on-click-modal="false">
      <div class="progress-info">
        <p>正在转换: {{ currentFile }}</p>
        <el-progress :percentage="progress" :status="progressStatus" />
        <p class="progress-tip">{{ progressTip }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelConvert">取消</el-button>
          <el-button type="primary" @click="downloadFile" :disabled="!isCompleted">
            下载
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadInstance } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const uploadRef = ref<UploadInstance>()
const targetFormat = ref('.pdf')
const showProgress = ref(false)
const progress = ref(0)
const currentFile = ref('')
const uploadedFileId = ref('')
const isCompleted = ref(false)

const progressStatus = computed(() => {
  if (progress.value === 100) return 'success'
  if (progress.value < 0) return 'exception'
  return ''
})

const progressTip = computed(() => {
  if (progress.value === 100) return '转换完成!'
  if (progress.value < 0) return '转换失败'
  return '正在转换中...'
})

const beforeUpload = (file: File) => {
  const maxSize = 100 * 1024 * 1024 // 100MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过100MB')
    return false
  }
  return true
}

const handleUploadSuccess = (response: any, file: any) => {
  if (response.success) {
    currentFile.value = file.name
    uploadedFileId.value = response.fileId
    startConversion()
  } else {
    ElMessage.error(response.error || '文件上传失败')
  }
}

const handleError = (error: any) => {
  console.error('文件上传错误:', error)
  let errorMessage = '文件上传失败'
  
  if (error.response) {
    try {
      const response = JSON.parse(error.response)
      errorMessage = response.error || errorMessage
    } catch (e) {
      if (typeof error.response === 'string') {
        errorMessage = error.response
      }
    }
  } else if (error.message) {
    errorMessage = error.message
  }
  
  ElMessage.error(errorMessage)
  progress.value = -1
}

const startConvert = () => {
  if (!targetFormat.value) {
    ElMessage.warning('请选择目标格式')
    return
  }
  
  // 开始上传文件
  uploadRef.value?.submit()
}

const startConversion = async () => {
  if (!uploadedFileId.value || !targetFormat.value) {
    ElMessage.error('缺少必要参数')
    return
  }

  showProgress.value = true
  progress.value = 0
  isCompleted.value = false

  try {
    const response = await fetch('/api/file/convert', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        fileId: uploadedFileId.value,
        targetFormat: targetFormat.value
      })
    })

    const data = await response.json()
    if (data.success) {
      startProgressCheck()
    } else {
      throw new Error(data.error || '转换失败')
    }
  } catch (error: any) {
    console.error('转换错误:', error)
    progress.value = -1
    ElMessage.error(error.message || '转换失败')
  }
}

const startProgressCheck = () => {
  const checkProgress = async () => {
    try {
      const response = await fetch(`/api/file/progress/${uploadedFileId.value}`)
      const data = await response.json()
      progress.value = data.progress
      if (progress.value === 100) {
        isCompleted.value = true
        return
      }
      if (progress.value >= 0) {
        setTimeout(checkProgress, 1000)
      }
    } catch (error) {
      progress.value = -1
      ElMessage.error('获取进度失败')
    }
  }
  checkProgress()
}

const cancelConvert = () => {
  showProgress.value = false
  progress.value = 0
  currentFile.value = ''
  uploadedFileId.value = ''
}

const downloadFile = async () => {
  try {
    // 获取转换后的文件信息
    const response = await fetch('/api/file/convert', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        fileId: uploadedFileId.value,
        targetFormat: targetFormat.value
      })
    })

    const data = await response.json()
    if (!data.success || !data.outputPath) {
      throw new Error('获取文件失败')
    }

    // 使用返回的outputPath下载文件
    const downloadResponse = await fetch(`/api/file/download/${data.outputPath}`)
    if (!downloadResponse.ok) {
      throw new Error('下载失败')
    }

    const blob = await downloadResponse.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    // 根据目标格式生成新的文件名
    const originalName = currentFile.value.replace(/\.[^/.]+$/, '') // 移除原始扩展名
    a.download = `${originalName}${targetFormat.value}` // 添加新的扩展名
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    showProgress.value = false
    ElMessage.success('下载成功')
  } catch (error: any) {
    console.error('下载错误:', error)
    ElMessage.error(error.message || '下载失败')
  }
}
</script>

<style scoped>
.file-convert {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 3rem;
}

.header-content {
  display: flex;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  position: relative;
}

.back-button {
  position: absolute;
  left: 2rem;
  text-decoration: none;
}

.title-container {
  flex: 1;
  text-align: center;
}

.header h1 {
  color: #303133;
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.subtitle {
  color: #606266;
  font-size: 1.2rem;
}

.upload-card {
  background: #fff;
  border-radius: 8px;
  padding: 2rem;
}

.upload-area {
  border: 2px dashed #e4e7ed;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.el-icon--upload {
  font-size: 4rem;
  color: #409EFF;
}

.upload-text h3 {
  font-size: 1.5rem;
  color: #303133;
  margin-bottom: 0.5rem;
}

.upload-text p {
  color: #909399;
}

.convert-options {
  margin-top: 2rem;
  text-align: center;
}

.convert-options h3 {
  margin-bottom: 1rem;
  color: #303133;
}

.format-buttons {
  margin-bottom: 2rem;
}

.convert-button {
  width: 200px;
  height: 50px;
  font-size: 1.2rem;
}

.progress-info {
  text-align: center;
  padding: 1rem;
}

.progress-tip {
  margin-top: 1rem;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}
</style> 